package com.sky.handler;

import com.sky.constant.MessageConstant;
import com.sky.exception.BaseException;
import com.sky.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver;

import java.sql.SQLIntegrityConstraintViolationException;
import java.util.List;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 捕获业务异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(BaseException ex){
        log.error("异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }

    /**
     * 用户名重复异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(SQLIntegrityConstraintViolationException ex){
        log.error("异常信息：{}", ex.getMessage());
        //Duplicate entry 'king3' for key 'employee.idx_username'
        //获取异常信息字符串
        String message = ex.getMessage();
        //判断字符串是否包含Duplicate entry字段
        if (message.contains("Duplicate entry")){
            //根据空格切割字符串
            String[] s = message.split(" ");
            return Result.error(s[2]+MessageConstant.ALREADY_EXIST);
        }else {
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
    }

    @ExceptionHandler
    public Result exceptionHandler(MethodArgumentNotValidException ex){
        //错误字段集合
        List<FieldError> fieldErrors = ex.getFieldErrors();
        //遍历集合，拿到全部
        for (FieldError fieldError : fieldErrors) {
            //拿到对应的错误信息
            String defaultMessage = fieldError.getDefaultMessage();
            log.info("参数错误信息：{}",defaultMessage);
            return Result.error(defaultMessage);
        }
        return Result.error(MessageConstant.UNKNOWN_ERROR);
    }


}
